#include <Adafruit_ST7735.h>
#include <Adafruit_GFX.h>
#include <SPI.h>
#include <TimeLib.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

#define LCD_BUTTON_UP         5
#define LCD_BUTTON_L         13
#define LCD_BUTTON_R          8
#define LCD_BUTTON_CENTER     4
#define LCD_BUTTON_DOWN       9
#define LCD_W                80
#define LCD_H               160

#define LCD_BL               11
#define LCD_CS                7
#define LCD_DC                6
#define LCD_RES              10
#define LCD_SDA               3
#define LCD_SCLK              2 
#define LCD_LD               30

#define blockup                1        // 按钮返回值定义
#define blockdown              2        //
#define blocklift              4        //
#define blockright             3        //
#define blockc                 5        //

#define LED 13

#define TIME_API_URL "http://worldtimeapi.org/api/timezone/Asia/Shanghai"
#define WEATHER_API_URL "http://api.weatherapi.com/v1/current.json?key=535acb6aa9584f69a39133219232805&q=Chengdu"
const char* WIFI_SSID = "MYHONOR";
const char* WIFI_PASSWORD = "xqf123456";

Adafruit_ST7735 tft = Adafruit_ST7735(LCD_CS,LCD_DC,LCD_SDA,LCD_SCLK,LCD_RES);  
void setup_buttons(){
  pinMode(LCD_BUTTON_DOWN,INPUT_PULLUP);
  pinMode(LCD_BUTTON_CENTER,INPUT_PULLUP);
  pinMode(LCD_BUTTON_L,INPUT_PULLUP);
  pinMode(LCD_BUTTON_UP,INPUT_PULLUP);
  pinMode(LCD_BUTTON_R,INPUT_PULLUP);   
}

unsigned int down_up(){
  int d,u,r,l,c;
  d=digitalRead(LCD_BUTTON_DOWN);
  u=digitalRead(LCD_BUTTON_UP);
  r=digitalRead(LCD_BUTTON_R);
  l=digitalRead(LCD_BUTTON_L);
  c=digitalRead(LCD_BUTTON_CENTER);
  if(d==LOW && r!=LOW && l!=LOW){
    //Serial.write("down!\n");
    return blockdown;
  }else if(u==LOW && r!=LOW && l!=LOW){
    //Serial.write("up!\n");
    return blockup;
  }else if(r==LOW && u!=LOW && d!=LOW){
    //Serial.write("right!\n");
    return blockright;
  }else if(l==LOW && u!=LOW && d!=LOW){
    //Serial.write("lift!\n");
    return blocklift;
  }else if(c==LOW){
    //Serial.write("center!\n");
    return blockc;
  }else{
    return 0;
  }
  //delay(50);
}

void bl_pwm(int16_t bfb) {
  int16_t t = int(255 * bfb / 100);
  analogWrite(LCD_BL, t);
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  tft.initR(INITR_MINI160x80);
  tft.setRotation(3);
  pinMode(LCD_BL, OUTPUT);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
  setup_buttons();
  bl_pwm(LCD_LD);
  tft.fillScreen(ST7735_BLACK);
  //tft.setTextColor(ST7735_WHITE);
}


bool isPaused = false; // 用于跟踪计时器的暂停状态
bool isButtonPressed = false; // 用于跟踪按钮按下状态
time_t pauseStartTime; // 记录暂停开始的时间
unsigned long totalPausedTime = 0; // 记录总的暂停时间
time_t startTime; // 记录计时开始的时间
int shift = 1;
enum Function {
  TIMER,
  TOMATO_CLOCK_WORK,
  TOMATO_CLOCK_BREAK,
  TIME_WEATHER
};

Function currentFunction = TIME_WEATHER; // 当前选定的功能
////////////////////////////////////////////////
void timer() {
  // 检测按钮状态
  unsigned int buttonState = down_up();
  
  // 判断是否按下了"center"按钮
  if (buttonState == blockc) {
        tft.fillRect(0, 0, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 20, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 40, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 60, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 80, tft.width(), 20, ST7735_BLACK);
    if (!isButtonPressed) {
      isButtonPressed = true;
      if (!isPaused) {
        // 第一次按下按钮，暂停计时并记录开始暂停的时间
        isPaused = true;
        pauseStartTime = now();
      } else {
        // 第二次按下按钮，重新开始计时
        isPaused = false;
        totalPausedTime = 0;
        startTime = now();
      }
    }
  } else if (buttonState == blockup || buttonState == blockdown) {
    if (!isButtonPressed) {
      isButtonPressed = true;
      if(buttonState == blockup){
        tft.fillRect(0, 0, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 20, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 40, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 60, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 80, tft.width(), 20, ST7735_BLACK);
        if(shift>=3)
        shift = 1;
        else
        shift++;
      }
      if(buttonState == blockdown){
        tft.fillRect(0, 0, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 20, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 40, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 60, tft.width(), 20, ST7735_BLACK);
        tft.fillRect(0, 80, tft.width(), 20, ST7735_BLACK);
        if(shift<=1)
        shift = 3;
        else
        shift--;
      }
      switch (shift){
        case 1: 
               currentFunction = TIME_WEATHER;
               break;
        case 2:
               currentFunction = TIMER;
               break;
        case 3:
               currentFunction = TOMATO_CLOCK_WORK;
               break;
      }
      // 重置计时器状态
      isPaused = false;
      totalPausedTime = 0;
      startTime = now();
    }
  } else {
    isButtonPressed = false;
  }

  // 根据当前选定的功能显示相应的内容
  if (currentFunction == TIMER) {
    // 计时器功能
    if (!isPaused) {
      // 计算经过的时间（减去累计的暂停时间）
      time_t currentTime = now();
      unsigned long elapsedMillis = (currentTime - startTime) * 1000;
      elapsedMillis -= totalPausedTime;

      // 将毫秒转换为时、分、秒
      int hourValue = elapsedMillis / 3600000;
      int minuteValue = (elapsedMillis / 60000) % 60;
      int secondValue = (elapsedMillis / 1000) % 60;

      char timeStr[9];
      sprintf(timeStr, "%02d:%02d:%02d", hourValue, minuteValue, secondValue);

  
      tft.setCursor(0, 0);
      tft.setTextSize(2);
      tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
      tft.println(timeStr);
      tft.setCursor(0, 20); // 将光标移动到下一行的起始位置
      tft.println("TIMER."); // 打印下一行的内容
      digitalWrite(LED, LOW); // 将LED引脚设置为低电平，熄灭LED
    } else {
      // 显示暂停状态
      //tft.fillRect(0, 0, tft.width(), 20, ST7735_BLACK);
      tft.setCursor(0, 0);
      tft.setTextSize(2);
      tft.println("Paused");
      digitalWrite(LED, LOW); // 将LED引脚设置为低电平，熄灭LED
    }
  } else if (currentFunction == TOMATO_CLOCK_WORK) {
    // 番茄钟功能（25秒）
      // 计算经过的时间（减去累计的暂停时间）
      time_t currentTime = now();
      unsigned long elapsedMillis = (currentTime - startTime) * 1000;
      elapsedMillis -= totalPausedTime;

      // 检查番茄钟周期
      unsigned long totalTime = 25000; // 25秒+5秒
      unsigned long remainingTime = totalTime - elapsedMillis;

      if (remainingTime <= 0) {
        // 番茄钟周期结束，重置计时器状态
        isPaused = true;
        totalPausedTime = 0;
        startTime = now();
        currentFunction = TOMATO_CLOCK_BREAK;
      } else {
        // 将毫秒转换为时、分、秒
        int secondValue = remainingTime / 1000;
        int millisecondValue = remainingTime % 1000;

        char timeStr[9];
        sprintf(timeStr, "%02d:%03d", secondValue, millisecondValue);

        tft.setTextSize(2);
        tft.setCursor(0, 0);
        tft.setTextColor(ST7735_BLUE, ST7735_BLACK);
        tft.println(timeStr);
        tft.setCursor(0, 20); // 将光标移动到下一行的起始位置
        tft.println("TOMATO_CLK_WORK."); // 打印下一行的内容
        digitalWrite(LED, LOW); // 将LED引脚设置为低电平，熄灭LED
      }
  }
  else if (currentFunction == TOMATO_CLOCK_BREAK){
    // 番茄钟功能（25秒）
      // 计算经过的时间（减去累计的暂停时间）
      
      time_t currentTime = now();
      unsigned long elapsedMillis = (currentTime - startTime) * 1000;
      elapsedMillis -= totalPausedTime;

      // 检查番茄钟周期
      unsigned long totalTime = 5000; // 25秒+5秒
      unsigned long remainingTime = totalTime - elapsedMillis;

      if (remainingTime <= 0) {
        // 番茄钟周期结束，重置计时器状态
        isPaused = true;
        totalPausedTime = 0;
        startTime = now();
        currentFunction = TOMATO_CLOCK_WORK;
      } else {
        // 将毫秒转换为时、分、秒
        int secondValue = remainingTime / 1000;
        int millisecondValue = remainingTime % 1000;

        char timeStr1[9];
        sprintf(timeStr1, "%02d:%03d", secondValue, millisecondValue);

        tft.setTextSize(2);
        tft.setCursor(0,0);
        tft.setTextColor(ST7735_YELLOW, ST7735_BLACK);
        tft.println(timeStr1);
        tft.setCursor(0, 20); // 将光标移动到下一行的起始位置
        tft.println("TOMATO_CLK_BREAK"); // 打印下一行的内容
        digitalWrite(LED, HIGH); // 将LED引脚设置为高电平，点亮LED
      }
  }
}

//实时显示时间
void displayTime(const char* timeStr) {
  tft.setCursor(0, 0);
  tft.setTextSize(2);
  tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
  tft.println(timeStr);
}
//显示天气
void displayWeather(const char* weatherStr) {
  tft.fillRect(0, 60, tft.width(), 40, ST7735_BLACK);
  tft.setCursor(0, 60);
  tft.setTextSize(2);
  tft.setTextColor(ST7735_CYAN, ST7735_BLACK);
  tft.println(weatherStr);
}
//从网络获取时间
void getTimeFromAPI() {
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to WiFi...");
  }

  HTTPClient timeClient;
  timeClient.begin(TIME_API_URL);
  int httpResponseCode = timeClient.GET();

  if (httpResponseCode == HTTP_CODE_OK) {
    String response = timeClient.getString();
    DynamicJsonDocument doc(1024);
    deserializeJson(doc, response);

    // 获取时间信息
    const char* timeStr = doc["datetime"];
    displayTime(timeStr);
  } else {
    Serial.printf("Time API request failed with error code %d\n", httpResponseCode);
  }

  timeClient.end();
}
//获取天气
void getWeatherFromAPI() {
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to WiFi...");
  }

  HTTPClient weatherClient;
  weatherClient.begin(WEATHER_API_URL);
  int httpResponseCode = weatherClient.GET();

  if (httpResponseCode == HTTP_CODE_OK) {
    String response = weatherClient.getString();
    DynamicJsonDocument doc(1024);
    deserializeJson(doc, response);

    // 获取天气信息
    const char* weatherStr = doc["current"]["condition"]["text"];
    displayWeather(weatherStr);
  } else {
    Serial.printf("Weather API request failed with error code %d\n", httpResponseCode);
  }

  weatherClient.end();
}

void loop() {
  timer();
  // 获取时间和天气信息
  if(currentFunction == TIME_WEATHER){
    getTimeFromAPI();
    getWeatherFromAPI(); 
  }
  //delay(10);
}